0987cd7282b9beda54ec90471715a239aaad3337
[nextcloud-desktop.git] /
1 //
2 //  ShareeSuggestionsDataSource.swift
3 //  FileProviderUIExt
4 //
5 //  Created by Claudio Cambra on 2/4/24.
6 //
7
8 import Foundation
9 import NextcloudFileProviderKit
10 import NextcloudKit
11 import OSLog
12 import SuggestionsTextFieldKit
13
14 class ShareeSuggestionsDataSource: SuggestionsDataSource {
15     let kit: NextcloudKit
16     let account: Account
17     var suggestions: [Suggestion] = []
18     var inputString: String = "" {
19         didSet { Task { await updateSuggestions() } }
20     }
21
22     init(account: Account, kit: NextcloudKit) {
23         self.account = account
24         self.kit = kit
25     }
26
27     private func updateSuggestions() async {
28         let sharees = await fetchSharees(search: inputString)
29         Logger.shareeDataSource.info("Fetched \(sharees.count, privacy: .public) sharees.")
30         suggestions = suggestionsFromSharees(sharees)
31         NotificationCenter.default.post(name: SuggestionsChangedNotificationName, object: self)
32     }
33
34     private func fetchSharees(search: String) async -> [NKSharee] {
35         Logger.shareeDataSource.debug("Searching sharees with: \(search, privacy: .public)")
36         return await withCheckedContinuation { continuation in
37             kit.searchSharees(
38                 search: inputString,
39                 page: 1,
40                 perPage: 20,
41                 account: account.ncKitAccount,
42                 completion: { account, sharees, data, error in
43                     defer { continuation.resume(returning: sharees ?? []) }
44                     guard error == .success else {
45                         Logger.shareeDataSource.error(
46                             "Error fetching sharees: \(error.description, privacy: .public)"
47                         )
48                         return
49                     }
50                 }
51             )
52         }
53     }
54
55     private func suggestionsFromSharees(_ sharees: [NKSharee]) -> [Suggestion] {
56         return sharees.map {
57             Suggestion(
58                 imageName: "person.fill",
59                 displayText: $0.label.isEmpty ? $0.name : $0.label,
60                 data: $0
61             )
62         }
63     }
64 }